/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import loginSocket from 'libloginSocket.so'
import registerSocket from 'libregisterSocket.so'
import mySocket from 'libsocket.so'
import Bus from './common/Bus'
// import Time from '@ohos.Time';
const passwordMemory = [
    {
        text: 'username001',
        imgUrl: 'common/images/personPic/1.png',
    },
    {
        text: 'username002',
        imgUrl: 'common/images/personPic/1.png',
    },
    {
        text: 'username003',
        imgUrl: 'common/images/personPic/1.png',
    },
];
let friendsList = [
    // 格式如下：
    //    {
    //        id: 1,
    //        imgUrl: '/common/images/sessionPic/img_' + Math.round(Math.random()*7+1) + '.png',
    //        text: '默认朋友',
    //        url: '',
    //        style: 'pengyou'
    //    }
    /*
    * 测试通讯录好友跳转----假数据
    */
        {
            id: 1,
            imgUrl: '/common/images/sessionPic/img_1.png',
            text: '213212',
            url: '',
            style: 'pengyou'
        },
        {
            id: 2,
            imgUrl: '/common/images/sessionPic/img_2.png',
            text: '123123',
            url: '',
            style: 'pengyou'
        }
]
let groupList = [
    {
        id: 1,
        imgUrl: '/common/images/sessionPic/img_1.png',
        text: '213212',
        url: '',
        style: 'pengyou'
    },
    {
        id: 2,
        imgUrl: '/common/images/sessionPic/img_2.png',
        text: '123123',
        url: '',
        style: 'pengyou'
    }
]
let groupMembersList = [
    /*
    * 测试群成员。访问每个群时，此数组可存放当前群组的成员列表
    ----假数据
    */
    {
        id: 1,
        imgUrl: '/common/images/sessionPic/img_1.png',
        text: '群成员测试1',
        url: '',
        style: 'pengyou'
    },
    {
        id: 2,
        imgUrl: '/common/images/sessionPic/img_2.png',
        text: '群成员测试2',
        url: '',
        style: 'pengyou'
    }
]
let mailList = [
    {
        id: 1,
        imgUrl: '/common/images/mailList/xindepengyou.png',
        text: '新的朋友',
        url: '',
        style: 'xindepengyou',
        find_right_icon: '', //'/common/images/mailList/newtip.png',
    }
]
let blackList = [
    // 黑名单假数据
    {
        id: 1,
        imgUrl: '/common/images/sessionPic/img_3.png',
        text: '213212',
        url: '',
        style: 'pengyou'
    },
    {
        id: 2,
        imgUrl: '/common/images/sessionPic/img_4.png',
        text: '123123',
        url: '',
        style: 'pengyou'
    }
]
var chatData = [
    /*
    * 测试聊天信息。存储每个session对象的聊天信息
    ----假数据
    */
    {
        'title': '蔡同学',
        'topMessage': '欢迎来到华为鸿蒙操作系统',
        'imgUrl': '/common/images/sessionPic/img_8.png',
        'readTime': '17:00',
        'unRead': 'say',
        'uid': [995645],
        'checkId': [],
        'MsgList': [
            {isMe: false,
                sendUid:"",
                messageType: 0,
                content:'华为鸿蒙系统是一款全新的面向全场景的分布式操作系统，创造一个超级虚拟终端互联的世界',
                profPicUrl:'/common/images/bob.jpg',
                createTime:"",},
            {isMe: false,
                sendUid:"",
                messageType: 1,
                content:'/common/images/harmonyos.jpg',
                profPicUrl:'/common/images/bob.jpg',
                createTime:"",}
                    ]
    },
    {
        'title': '群组聊天',
        'topMessage': '今日工作日报',
        'imgUrl': '/common/images/sessionPic/img_1.png',
        'readTime': '10:00',
        'unRead': 'group',
        'uid': [1],
        'checkId': [],
        'MsgList': [
            {isMe: false,
                sendUid:"",
                messageType: 0,
                content:'华为鸿蒙系统是一款全新的面向全场景的分布式操作系统，创造一个超级虚拟终端互联的世界',
                profPicUrl:'/common/images/bob.jpg',
                createTime:"",},
            {isMe: false,
                sendUid:"",
                messageType: 1,
                content:'/common/images/harmonyos.jpg',
                profPicUrl:'/common/images/bob.jpg',
                createTime:"",}
        ]
    },
];

export default {
//    ip: '192.168.31.203:8099', //http服务器地址：需要指定端口号
//    ip: '124.16.141.248:8099',
    ip: '124.16.138.128:8099',
//    socketIP: '192.168.31.203', //tcp服务器地址：端口号为1884
//    socketIP: '124.16.141.248',
    socketIP: '124.16.138.128',
    eventBus: Bus,
    uri: [1],
    connectStatus: 0,
    //    mysocket:socket,
    loginSocket: loginSocket,
    registerSocket: registerSocket,
    mySocket: mySocket,
    uid: '123211',
    nickname: "APPJS默认昵称", // 用户本人昵称
    idx: 0,
    msg: "",
    chatData: chatData,
    friendsList: friendsList,
    memory:passwordMemory,
    groupList: groupList,
    groupMembersList: groupMembersList,
    mailList: mailList,
    blackList: blackList,
    //message content
    agreeuid: '',
    sessionuid: '',
    sessiontype: '',
    dialogcontent: '',
    checkedId: [],
    mailFriendId: -1,
    //显示当前是删除还是撤回
    deleteOrRecall:'删除',
    message: {
        uid: '',
        touid: [],
        role: '',
        type: '',
        content: '',
        stype: ''
    },
    onCreate() {
        console.info("Application onCreate");
        //修改此处为服务器地址和端口号
        //        this.loginSocket.connect("192.168.1.110",8090);
        //        console.info("loginSocket.connect");
        //        this.registerSocket.connect("192.168.1.110",8080);
        console.info("mySocket=====connect ready");
        this.mySocket.connect(this.socketIP, 1884);
        console.info("mySocket=====connect");
        //        setInterval(this.socketReceive ,2000);
        this.demo();

        // setInterval();
    },
    onDestroy() {
        console.info("Application onDestroy");
    },
    demo() {
        console.info('mySocket=====demo')
        this.socketReceive()
        var that = this
        setTimeout(function () {
            that.demo()
        }, 500);
    },
    socketReceive() {
        console.info("app.js=====socketReceive");
        var message = this.mySocket.receive();
        console.info("app.js====message:" + message);
        if (message == '\0') {
            console.info("app.js==== message:0");
            return;
        }

        let jsonMsg = {}
        try {
            jsonMsg = JSON.parse(message.substring(message.lastIndexOf('{'), message.lastIndexOf('}')+1))
            console.info("app.js====jsonmsg:" + JSON.stringify(jsonMsg));
        } catch (error) {
            console.info("app.js=====jsonmsg error:" + error);
        }

        const arr = message.split('"');
        console.info("app.js=====arr[11]:" + arr[11].trim());
        switch (jsonMsg.type) {
        //添加好友
            case 'addFriend':
                console.log('app.js=====addFriend')
                //“好友”按钮的徽标
                this.eventBus.$emit('refreshIndexToast',1)
            //this.agreeuid = this.message.uid;
//                this.agreeuid = ((arr[2].replace(':', '')).replace(',', ''));
                this.agreeuid = jsonMsg.uid;
                console.log('app.js=====this.agreeuid' + this.agreeuid);
                break;
        //私聊
            case 'say':
                this.eventBus.$emit('refreshIndexToast',0)
                if(jsonMsg.stype === 0) {
                    console.info("app.js=====say");
                    this.dialogcontent = jsonMsg.content;
                    let friendUid = jsonMsg.uid
                    let friendIndex = this.chatData.findIndex(item => {
                        return item.uid[0] == friendUid && item.unRead == 'say'
                    })
                    if (friendIndex === -1) {
                        this.addItem(friendUid)
                        friendIndex = 0
                        this.eventBus.$emit('refreshSessionList')
                    }
                    console.info("app.js=====this.chatData[this.idx].MsgList.push:" + this.chatData[this.idx].MsgList);
                    this.chatData[friendIndex].MsgList.push({
                        isMe: false,
                        sendUid:jsonMsg.uid,
                        messageType: 0,
                        content: this.dialogcontent,
                        profPicUrl: '/common/images/bob.jpg',
                        createTime:jsonMsg.timestamp,
                    }
                    );
                    console.info("app.js=====this.chatData[this.idx].MsgList.push OK:" + this.chatData[this.idx].MsgList);
                } else if(jsonMsg.stype === 1) {
                    console.info("app.js=====imageSay");
                    let contentImage = jsonMsg.content;
                    let friendUid_imageSay = jsonMsg.uid;
                    let friendIndex_imageSay = this.chatData.findIndex(item => {return item.uid[0] == friendUid_imageSay && item.unRead == 'say'})
                    if(friendIndex_imageSay === -1) {
                        this.addItem(friendUid_imageSay)
                        friendIndex_imageSay = 0
                        this.eventBus.$emit('refreshSessionList')
                    }
                    console.info("app.js=====this.chatData[this.idx].MsgList.push:" + this.chatData[this.idx].MsgList);
                    this.chatData[friendIndex_imageSay].MsgList.push({
                        isMe: false,
                        sendUid:jsonMsg.uid,
                        messageType: 1,
                        content: 'http://' + contentImage,
                        profPicUrl: '/common/images/bob.jpg',
                        createTime:jsonMsg.timestamp,
                    });
                    console.info("app.js=====this.chatData[this.idx].MsgList.push OK:" + this.chatData[this.idx].MsgList);
                } else if(jsonMsg.stype === 2) {
                    // 文件消息
                    console.info("app.js=====fileSay");
                    let contentFile = jsonMsg.content;
                    let fileName = contentFile.substring(contentFile.lastIndexOf("/") + 1);
                    let fileType = contentFile.substring(contentFile.lastIndexOf(".") + 1);
                    let friendUid_fileSay = jsonMsg.uid;
                    let friendIndex_fileSay = this.chatData.findIndex(item => {return item.uid[0] == friendUid_fileSay && item.unRead == 'say'})
                    if(friendIndex_fileSay === -1) {
                        this.addItem(friendUid_fileSay)
                        friendIndex_fileSay = 0
                    }
                    console.info("app.js=====this.chatData[this.idx].MsgList.push:" + this.chatData[this.idx].MsgList);
                    let receiveContent = {
                        "fileUrl" : 'http://' + contentFile,
                        "fileName" : fileName,
                        "fileType" : fileType,
                    }
                    this.chatData[friendIndex_fileSay].MsgList.push({
                        isMe: false,
                        sendUid:jsonMsg.uid,
                        messageType: 'file',
                        content: receiveContent,
                        createTime:jsonMsg.timestamp,
                    });
                } else if(jsonMsg.stype === 3) {
                    console.info("app.js=====audioSay");
                    let content_audioSay = jsonMsg.content;
                    let friendUid_audioSay = jsonMsg.uid;
                    let friendIndex_audioSay = this.chatData.findIndex(item => {return item.uid[0] == friendUid_audioSay && item.unRead == 'say'})
                    if(friendIndex_audioSay === -1) {
                        this.addItem(friendUid_audioSay)
                        friendIndex_audioSay = 0
                        this.eventBus.$emit('refreshSessionList')
                    }
                    console.info("app.js=====this.chatData[this.idx].MsgList.push:" + this.chatData[this.idx].MsgList);
                    this.chatData[friendIndex_audioSay].MsgList.push({
                        isMe: false,
                        sendUid:jsonMsg.uid,
                        messageType: 'audio',
                        content: {
                            path: 'http://' + content_audioSay,
                            dataTime:"语音消息，点击播放",
                            file: '',
                            date: '',
                            hasSend: true
                        },
                        profPicUrl: '/common/images/bob.jpg',
                        createTime:jsonMsg.timestamp,
                    });
                    console.info("app.js=====this.chatData[this.idx].MsgList.push OK:" + this.chatData[this.idx].MsgList);
                }
                //emoji表情的接收
                else if(jsonMsg.stype === 4) {
                    console.info("app.js=====imageSay");
                    let contentImage = jsonMsg.content;
                    let friendUid_imageSay = jsonMsg.uid;
                    let friendIndex_imageSay = this.chatData.findIndex(item => {return item.uid[0] == friendUid_imageSay && item.unRead == 'say'})
                    if(friendIndex_imageSay === -1) {
                        this.addItem(friendUid_imageSay)
                        friendIndex_imageSay = 0
                        this.eventBus.$emit('refreshSessionList')
                    }
                    console.info("app.js=====this.chatData[this.idx].MsgList.push:" + this.chatData[this.idx].MsgList);
                    this.chatData[friendIndex_imageSay].MsgList.push({
                        isMe: false,
                        sendUid:jsonMsg.uid,
                        messageType: 2,
                        content: '/common/images/face/Expression_' + contentImage + '.png',
                        profPicUrl: '/common/images/bob.jpg',
                        createTime:jsonMsg.timestamp,
                    });
                    console.info("app.js=====this.chatData[this.idx].MsgList.push OK:" + this.chatData[this.idx].MsgList);
                }
                break;
        // 添加好友通过
            case 'addFriendPass':
                console.info("app.js=====addFriendPass");
                this.sessionuid = ((arr[2].replace(':', '')).replace(',', ''));
                console.info("app.js=====sessionuid:" + this.sessionuid);
                this.addItem(this.sessionuid)
                this.eventBus.$emit('refreshSessionList')
                this.eventBus.$emit('refreshMailList')
                break;
        //撤回个人消息
            case 'withdrawSay':
                console.info("app.js=====withdrawSay");
                let friendsUid = jsonMsg.uid;
                let friendIndex = this.chatData.findIndex(item => {return item.uid[0] == friendsUid && item.unRead == 'say'})
                console.info("app.js=====say==withdrawSay==friendIndex:" + friendIndex);
                this.chatData[friendIndex].MsgList.pop();
                console.info("app.js=====say==withdrawSay==MsgList:" + this.chatData[friendIndex].MsgList);
                break;
        //撤回群聊消息
            case 'withdrawGroup':
                console.info("app.js=====withdrawGroup");
                let groupUid = jsonMsg.touid;
                let groupIndex = this.chatData.findIndex(item => {return item.uid[0] == groupUid && item.unRead == 'group'})
                console.info("app.js=====say==withdrawGroup==friendIndex:" + groupIndex);
                this.chatData[groupIndex].MsgList.pop();
                console.info("app.js=====say==withdrawGroup==MsgList:" + this.chatData[groupIndex].MsgList);
                break;
        //群发
            case 'group':
                //“主页”按钮的徽标
                this.eventBus.$emit('refreshIndexToast',0)
                if(jsonMsg.stype === 0) {
                    console.info("app.js=====group");
                    let content = jsonMsg.content;
                    // 成员id
                    let checkedId = [];
                    // 群聊id
                    let groupId = jsonMsg.touid[0]; //群聊id从后端拿过来
                    let index = this.chatData.findIndex(item => {
                        return item.uid[0] == groupId && item.unRead == 'group'
                    })
                    if (index === -1) {
                        this.addGroupItem(groupId, checkedId)
                        index = 0
                        this.eventBus.$emit('refreshSessionList')
                    }
                    //添加消息
                    this.chatData[index].MsgList.push({
                        isMe: false,
                        sendUid:jsonMsg.uid,
                        messageType: 0,
                        content: content,
                        profPicUrl: '/common/images/bob.jpg',
                        createTime:jsonMsg.timestamp,
                    });
                } else if(jsonMsg.stype === 1) {
                    console.info("app.js=====group");
                    let content_imageGroup = jsonMsg.content;
                    // 成员id
                    let checkedId_imageGroup = [];
                    // 群聊id
                    let groupId_imageGroup = jsonMsg.touid[0]; //群聊id从后端拿过来
                    let index_imageGroup = this.chatData.findIndex(item => {return item.uid[0] == groupId_imageGroup && item.unRead == 'group'})
                    if(index_imageGroup === -1) {
                        this.addGroupItem(groupId_imageGroup, checkedId_imageGroup)
                        index_imageGroup = 0
                        this.eventBus.$emit('refreshSessionList')
                    }
                    //添加消息
                    this.chatData[index_imageGroup].MsgList.push({
                        isMe: false,
                        sendUid:jsonMsg.uid,
                        messageType: 1,
                        content: 'http://' + content_imageGroup,
                        profPicUrl: '/common/images/bob.jpg',
                        createTime:jsonMsg.timestamp,
                    });
                } else if(jsonMsg.stype === 2) {
                    console.info("app.js=====fileGroup");
                    let content_fileGroup = jsonMsg.content;
                    // 成员id
                    let checkedId_fileGroup = [];
                    // 群聊id
                    let groupId_fileGroup = jsonMsg.touid[0];//群聊id从后端拿过来
                    let fileName = content_fileGroup.substring(content_fileGroup.lastIndexOf("/") + 1);
                    let fileType = content_fileGroup.substring(content_fileGroup.lastIndexOf(".") + 1);

                    let index_fileGroup = this.chatData.findIndex(item => {return item.uid[0] == groupId_fileGroup && item.unRead == 'group'})
                    if(index_fileGroup === -1) {
                        this.addGroupItem(groupId_fileGroup, checkedId_fileGroup)
                        index_fileGroup = 0
                    }
                    let receiveContent = {
                        "fileUrl" : 'http://' + content_fileGroup,
                        "fileName" : fileName,
                        "fileType" : fileType,
                    }
                    // 添加消息
                    this.chatData[index_fileGroup].MsgList.push({
                        isMe: false,
                        sendUid:jsonMsg.uid,
                        messageType: 'file',
                        content: receiveContent,
                        profPicUrl: '/common/images/bob.jpg',
                        createTime:jsonMsg.timestamp,
                    });
                }else if(jsonMsg.stype === 3) {
                    console.info("app.js=====group");
                    let content_audioGroup = jsonMsg.content;
                    // 成员id
                    let checkedId_audioGroup = [];
                    // 群聊id
                    let groupId_audioGroup = jsonMsg.touid[0]; //群聊id从后端拿过来
                    let index_audioGroup = this.chatData.findIndex(item => {return item.uid[0] == groupId_audioGroup && item.unRead == 'group'})
                    if(index_audioGroup === -1) {
                        this.addGroupItem(groupId_audioGroup, checkedId_audioGroup)
                        index_audioGroup = 0
                        this.eventBus.$emit('refreshSessionList')
                    }
                    //添加消息
                    this.chatData[index_audioGroup].MsgList.push({
                        isMe: false,
                        sendUid:jsonMsg.uid,
                        messageType: 'audio',
                        content: {
                            path: 'http://' + content_audioGroup,
                            dataTime:"语音消息，点击播放"
                        },
                        profPicUrl: '/common/images/bob.jpg',
                        createTime:jsonMsg.timestamp,
                    });
                }
                //emoji表情的接收
                else if(jsonMsg.stype === 4) {
                    console.info("app.js=====emojiSay");
                    let contentImage = jsonMsg.content;
                    // 成员id
                    let checkedId_emojiGroup = [];
                    let groupId_emojiGroup = jsonMsg.touid[0]; //群聊id从后端拿过来
                    let index_emojiGroup = this.chatData.findIndex(item => {return item.uid[0] == groupId_emojiGroup && item.unRead == 'group'})
                    if(index_emojiGroup === -1) {
                        this.addGroupItem(groupId_emojiGroup,checkedId_emojiGroup)
                        index_emojiGroup = 0
                        this.eventBus.$emit('refreshSessionList')
                    }
                    console.info("app.js=====this.chatData[this.idx].MsgList.push:" + this.chatData[index_emojiGroup].MsgList);
                    this.chatData[index_emojiGroup].MsgList.push({
                        isMe: false,
                        sendUid:jsonMsg.uid,
                        messageType: 2,
                        content: '/common/images/face/Expression_' + contentImage + '.png',
                        profPicUrl: '/common/images/bob.jpg',
                        createTime:jsonMsg.timestamp,
                    });
                }
                break;
            default:
                console.info("app.js=====default");
                break;
        }
    },
    addGroupItem(groupId, checkedId) {
        console.info("app.js=====addGroupItem:sessionuid == " + groupId);
        let img = '/common/images/sessionPic/img_' + Math.round(Math.random() * 7 + 1) + '.png'
        console.info("app.js===== img selected");
        let newSession = {
            'title': groupId,
            'topMessage': '欢迎加入群聊',
            'imgUrl': img,
            'readTime': new Date().getHours() + ':' + new Date().getMinutes(),
            'unRead': 'group',
            'uid': [groupId],
            'checkId': checkedId,
            'MsgList': [{isMe: false,
                            sendUid:"",
                            messageType: 0,
                            content:'华为鸿蒙系统是一款全新的面向全场景的分布式操作系统，创造一个超级虚拟终端互联的世界',
                            profPicUrl:'/common/images/bob.jpg',
                            createTime:"",},
                        {isMe: false,
                            sendUid:"",
                            messageType: 1,
                            content:'/common/images/harmonyos.jpg',
                            profPicUrl:'/common/images/bob.jpg',
                            createTime:"",}]
        }
        console.info("app.js===== let newSession");
        this.chatData = [newSession, ...this.chatData]
    },
    addItem(sessionuid) {
        console.info("app.js=====addItem:sessionuid == " + sessionuid);
        let img = '/common/images/sessionPic/img_' + Math.round(Math.random() * 7 + 1) + '.png'
        console.info("app.js===== img selected");
        let newSession = {
            'title': sessionuid,
            'topMessage': '你们已经成为好友了',
            'imgUrl': img,
            'readTime': new Date().getHours() + ':' + new Date().getMinutes(),
            'unRead': 'say',
            'uid': [sessionuid],
            'checkId': [],
            'MsgList': [{isMe: false,
                            sendUid:"",
                            messageType: 0,
                            content:'华为鸿蒙系统是一款全新的面向全场景的分布式操作系统，创造一个超级虚拟终端互联的世界',
                            profPicUrl:'/common/images/bob.jpg',
                            createTime:"",},
                        {isMe: false,
                            sendUid:"",
                            messageType: 1,
                            content:'/common/images/harmonyos.jpg',
                            profPicUrl:'/common/images/bob.jpg',
                            createTime:"",}]
        }
        console.info("app.js===== let newSession");
        let newFriend = {
            id: this.friendsList.length + 1,
            imgUrl: img,
            text: sessionuid,
            url: '',
            style: 'pengyou',
            find_right_icon: '/common/images/findPic/find-right-icon.png'
        }
        console.info("app.js===== let newFriend");
        console.info("app.js===== chatData length" + this.chatData.length);
        this.chatData = [newSession, ...this.chatData]
        console.info("app.js===== chatData length" + this.chatData.length);
        console.info("app.js===== chatData length" + JSON.stringify(this.chatData));
        this.friendsList = [newFriend, ...this.friendsList]
    }
};
